import NavBar from '@/components/NavBar';
import { useAppDispatch, useAppSelector } from '@/store';
import { clearInfoAction, getProfileAction, updateProfileAction } from '@/store/action/user';
import { List, Modal, Popup } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import { uploadPhotoAction } from '@/store/action/user';
import { Toast } from 'antd-mobile';
import { IProfile } from '@/store/reducer/user';
import Input from '@/components/Input';
import TextArea from '@/components/TextArea';
import { DatePicker } from 'antd-mobile';
import dayjs from 'dayjs';
import { removeAuth } from '@/utils/storage';
import history from '@/utils/history';

type EditType = 'photo' | 'gender' | 'name' | 'intro';

export default function ProfileEdit() {
  const dispatch = useAppDispatch();
  const { profile } = useAppSelector((state) => state.user);

  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);
  const [editType, setEditType] = useState('' as EditType);

  const [name, setName] = useState('');
  const [intro, setIntro] = useState('');

  useEffect(() => {
    setIntro(profile.intro);
    setName(profile.name);
  }, [profile]);

  useEffect(() => {
    dispatch(getProfileAction());
  }, [dispatch]);

  const iptRef = useRef<HTMLInputElement>(null);

  const handleShowPopup = (type: EditType) => {
    setEditType(type);
    if (type === 'photo' || type === 'gender') setVisible(true);
    if (type === 'intro' || type === 'name') setRightVisible(true);
  };

  const handleShowUpload = () => {
    iptRef.current?.click();
  };

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) {
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      await dispatch(uploadPhotoAction(formData));
      handleRefresh();
    }
  };

  const handleUpdateProfile = async (profile: Partial<IProfile>) => {
    await dispatch(updateProfileAction(profile));
    handleRefresh();
  };

  const handleRefresh = () => {
    dispatch(getProfileAction());
    Toast.show('更新成功');
    setVisible(false);
    setRightVisible(false);
  };

  const renderGenderOrPhoto = () => {
    if (editType === 'gender') {
      return (
        <>
          <div onClick={() => handleUpdateProfile({ gender: 0 })} className="list-item">
            男
          </div>
          <div onClick={() => handleUpdateProfile({ gender: 1 })} className="list-item">
            女
          </div>
        </>
      );
    }

    if (editType === 'photo') {
      return (
        <>
          <div onClick={handleShowUpload} className="list-item">
            拍照
          </div>
          <div onClick={handleShowUpload} className="list-item">
            本地选择
          </div>
        </>
      );
    }
  };

  const handleBack = () => {
    setName(profile.name);
    setIntro(profile.intro);
    setRightVisible(false);
  };

  const renderNameOrIntro = () => {
    const params: { name?: string; intro?: string } = {};
    let title = '';
    if (editType === 'name') {
      params.name = name;
      title = '昵称';
    }
    if (editType === 'intro') {
      params.intro = intro;
      title = '简介';
    }

    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span className="submit-btn" onClick={() => handleUpdateProfile(params)}>
              提交
            </span>
          }
        >
          编辑{title}
        </NavBar>
        <div className="edit-content">
          {editType === 'name' && (
            <Input className="edit-input" value={name} onChange={(e) => setName(e.target.value)} />
          )}
          {editType === 'intro' && (
            <TextArea value={intro} onChange={(e) => setIntro(e.target.value)} />
          )}
        </div>
      </>
    );
  };

  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              onClick={() => handleShowPopup('photo')}
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item arrow extra={profile.name} onClick={() => handleShowPopup('name')}>
              昵称
            </List.Item>

            <List.Item
              arrow
              onClick={() => handleShowPopup('intro')}
              extra={<span className="intro">{profile.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup('gender')}
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
            >
              性别
            </List.Item>
            <List.Item
              onClick={() => setBirthVisible(true)}
              arrow
              extra={profile.birthday?.slice(0, 10)}
            >
              生日
            </List.Item>
          </List>

          <input ref={iptRef} onChange={handleUpload} className="avatar-upload" type="file" />
        </div>

        <div className="logout">
          <button
            className="btn"
            onClick={() => {
              Modal.confirm({
                title: '温馨提示',
                content: '确认退出吗?',
                onConfirm: () => {
                  removeAuth();
                  Toast.show('退出成功');
                  history.push('/login');
                  dispatch(clearInfoAction());
                },
              });
            }}
          >
            退出登录
          </button>
        </div>
      </div>
      <Popup visible={visible} position="bottom" bodyClassName="popup-bottom-list">
        {renderGenderOrPhoto()}

        <div onClick={() => setVisible(false)} className="list-item">
          取消
        </div>
      </Popup>
      <Popup destroyOnClose visible={rightVisible} position="right" bodyClassName="popup-right">
        {renderNameOrIntro()}
      </Popup>
      <DatePicker
        value={new Date(profile.birthday?.slice(0, 10))}
        visible={birthVisible}
        onClose={() => setBirthVisible(false)}
        title="选择生日"
        min={new Date('1901-01-01')}
        max={new Date()}
        onConfirm={(val) => {
          handleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
        }}
      />
    </div>
  );
}
